package top.frsf.manage.service;// 引入必要的包
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.client.RestTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import top.frsf.common.core.domain.entity.SysUser;
import top.frsf.system.service.ISysUserService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class WeChatAuthService {
    @Autowired
    private ISysUserService userService;
    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    // 微信接口地址
    private static final String WX_AUTH_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信登录认证
     * @param code 前端传来的微信登录code
     * @return 包含自定义登录态和用户信息的结果
     */
    public Map<String, Object> wechatLogin(String code) {
        Map<String, Object> result = new HashMap<>();

        // 1. 构建请求URL
        String url = WX_AUTH_URL + "?appid=" + appid + "&secret=" + secret +
                "&js_code=" + code + "&grant_type=authorization_code";

        // 2. 向微信服务器发送请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);

        // 3. 解析微信返回结果
        JSONObject jsonObject = JSONObject.parseObject(response);
        String openid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");
        String unionid = jsonObject.getString("unionid");
        Integer errcode = jsonObject.getInteger("errcode");

        // 4. 检查微信接口是否返回错误
        if (errcode != null && errcode != 0) {
            result.put("status", "error");
            result.put("message", "微信认证失败: " + jsonObject.getString("errmsg"));
            return result;
        }

        // 5. 根据openid查找或创建用户
        SysUser  user = userService.findByOpenId(openid);
        if (user == null) {
            // 新用户，创建用户记录
            user = new SysUser();
            user.setOpenid(openid);
            user.setUnionid(unionid);
            user.setCreateTime(new Date());
            userService.insertUser(user);
        }

        // 6. 生成自定义登录态(token)
        String token = generateToken(user);

        // 7. 存储session_key (可选，如果需要解密用户信息)
        redisTemplate.opsForValue().set("session_key:" + openid, sessionKey, 7, TimeUnit.DAYS);

        // 8. 返回结果
        result.put("status", "success");
        result.put("token", token);
        result.put("userInfo", getUserInfo(user));

        return result;
    }

    /**
     * 生成自定义登录态token
     */
    private String generateToken(SysUser user) {
        // 使用JWT或自定义算法生成token
        String token = UUID.randomUUID().toString().replace("-", "");

        // 存储token与用户关联关系
        redisTemplate.opsForValue().set("token:" + token, user.getUserId().toString(), 7, TimeUnit.DAYS);

        return token;
    }

    /**
     * 获取用户信息
     */
    private Map<String, Object> getUserInfo(SysUser user) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userId", user.getUserId());
        userInfo.put("nickname", user.getNickname());
        userInfo.put("avatar", user.getAvatar());
        // 其他用户信息...
        return userInfo;
    }
}